package ru.mcfr.oxygen.util.ui;

import ro.sync.ecss.extensions.api.AuthorDocumentController;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ru.mcfr.oxygen.util.web.CommonSchemasGetter;
import ru.mcfr.oxygen.util.web.DocumentTypesGetter;
import ru.mcfr.oxygen.util.web.ItemInfo;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Properties;
import java.util.Set;

public class SchemaSelectorWindow extends JDialog {

    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JToggleButton jToggleButton4;
    private javax.swing.JToggleButton jToggleButton5;
    private javax.swing.JList schemasList1;
    private javax.swing.JList typesList1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private DocumentTypesGetter documentTypesGetter;
    private CommonSchemasGetter commonSchemas;
    private Set<ItemInfo> docTypes;
    private Set<ItemInfo> schemas;
    private Properties props = new Properties();
    private AuthorDocumentController docController;
    private ItemInfo currentSchemaInfo;

    private Color colorfor = null;

    public SchemaSelectorWindow(Properties p) {
        this.props = p;
        documentTypesGetter = new DocumentTypesGetter(this.props);
        commonSchemas = new CommonSchemasGetter(this.props);
        initComponents();
    }

    public SchemaSelectorWindow(Properties p, AuthorDocumentController controller) {
        this.props = p;
        this.docController = controller;
        documentTypesGetter = new DocumentTypesGetter(this.props);
        commonSchemas = new CommonSchemasGetter(this.props);

        try {
            AuthorElement authorNode = docController.getAuthorDocumentNode().getRootElement();
            String id = authorNode.getAttribute("id").getValue();
            String url = authorNode.getAttribute("xsi:noNamespaceSchemaLocation").getValue();
            currentSchemaInfo = new ItemInfo(id, "new schema", url);
        } catch (Exception e) {
            e.printStackTrace();
        }

        AuthorElement authorNode = docController.getAuthorDocumentNode().getRootElement();
        String sid = "";
        try {
            sid = authorNode.getAttribute("type").getValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String surl = "";
        try {
            surl = authorNode.getAttribute("xsi:noNamespaceSchemaLocation").getValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.currentSchemaInfo = new ItemInfo(sid, "", surl);

        initComponents();
    }

    private int curentType = 0;
    private int currentSchema = 0;

    abstract class MyCellRenderer extends JLabel implements ListCellRenderer {

        public MyCellRenderer() {
            setOpaque(false);
        }

        public Component
        getListCellRendererComponent(JList list,
                                     Object value, // value to display
                                     int index,    // cell index
                                     boolean iss,  // is selected
                                     boolean chf)  // cell has focus?
        {

            ItemInfo thisValue = (ItemInfo) value;
            this.setText(thisValue.title + " (id:" + thisValue.id + ")");

            if (markIfSelected(thisValue, index)) {
                //if (index == 5){
                this.setBackground(colorfor);
                this.setForeground(Color.red);
            } else {
                this.setBackground(Color.white);
                this.setForeground(Color.black);
            }

            if (iss) {
                this.setBorder(BorderFactory.createLineBorder(new Color(170, 210, 230), 1));
            } else {
                this.setBorder(BorderFactory.createLineBorder(list.getBackground(), 1));
            }

            return this;
        }

        protected abstract boolean markIfSelected(ItemInfo thisValue, int index);
    }

    class MyTypeCellRenderer extends MyCellRenderer {

        public MyTypeCellRenderer() {
            super();
        }

        @Override
        protected boolean markIfSelected(ItemInfo thisValue, int index) {
            if (thisValue.id.equalsIgnoreCase(currentSchemaInfo.id)) {
                curentType = index;
                return true;
            } else return false;
        }
    }

    class MySchemaCellRenderer extends MyCellRenderer {

        public MySchemaCellRenderer() {
            super();
        }

        @Override
        protected boolean markIfSelected(ItemInfo thisValue, int index) {
            if (thisValue.url.equalsIgnoreCase(currentSchemaInfo.url)) {
                currentSchema = index;
                return true;
            } else return false;
        }
    }

    private void initComponents() {
        this.colorfor = new Color(170, 210, 230);
        this.setTitle("Схема и тип документа");
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        typesList1 = new javax.swing.JList();
        typesList1.setCellRenderer(new MyTypeCellRenderer());
        jScrollPane4 = new javax.swing.JScrollPane();
        schemasList1 = new javax.swing.JList();
        schemasList1.setCellRenderer(new MySchemaCellRenderer());
        jToggleButton4 = new javax.swing.JToggleButton();
        jToggleButton5 = new javax.swing.JToggleButton();
        //10.0.65.13/schemaes/get_schemaes_list/
        DefaultListModel listModel = new DefaultListModel();
        docTypes = documentTypesGetter.getTypesFromURL(props.getProperty("url-to-docTypes"));//"http://10.0.65.13/mtypes/get_types_list/");
        int selected = 0;
        int counter = 0;
        for (ItemInfo schema : docTypes) {
            listModel.addElement(schema);
            if (currentSchemaInfo.id.equalsIgnoreCase(schema.id))
                selected = counter;
            counter++;

        }

        typesList1.setModel(listModel);

        //typesList1.setSelectedIndex(selected);

        typesList1.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent arg0) {
                if (arg0.getClickCount() == 2) {
                    assignSchema();
                }
            }

            public void mouseEntered(MouseEvent arg0) {

            }

            public void mouseExited(MouseEvent arg0) {

            }

            public void mousePressed(MouseEvent arg0) {

            }

            public void mouseReleased(MouseEvent arg0) {

            }

        });


        jScrollPane3.setViewportView(typesList1);

        jTabbedPane2.addTab("Типы", jScrollPane3);

        DefaultListModel listModel2 = new DefaultListModel();
        schemas = commonSchemas.getSchemasFromURL(props.getProperty("url-to-shemas"));//"http://10.0.65.13/schemaes/get_schemaes_list/");

        counter = 0;
        selected = 0;
        for (ItemInfo schema : schemas) {
            listModel2.addElement(schema);
            if (schema.url.equalsIgnoreCase(currentSchemaInfo.url))
                selected = counter;
            counter++;
        }

        schemasList1.setModel(listModel2);

        //schemasList1.setSelectedIndex(selected);


        schemasList1.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent arg0) {
                if (arg0.getClickCount() == 2) {
                    assignSchema();
                }
            }

            public void mouseEntered(MouseEvent arg0) {

            }

            public void mouseExited(MouseEvent arg0) {

            }

            public void mousePressed(MouseEvent arg0) {

            }

            public void mouseReleased(MouseEvent arg0) {

            }

        });

        jScrollPane4.setViewportView(schemasList1);

        jTabbedPane2.addTab("Схемы", jScrollPane4);

        jTabbedPane2.addChangeListener(new ChangeListener() {

            public void stateChanged(ChangeEvent arg0) {
                //changeTitle("selected tab is: " + jTabbedPane2.getSelectedIndex());
                typesList1.ensureIndexIsVisible(curentType);
                schemasList1.ensureIndexIsVisible(currentSchema);
                if (jTabbedPane2.getSelectedIndex() == 0)
                    jToggleButton5.setText("Назначить тип");
                if (jTabbedPane2.getSelectedIndex() == 1)
                    jToggleButton5.setText("Назначить схему");
            }

        });

        jToggleButton4.setText("Закрыть");
        jToggleButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeSchemaSelectionFrame();
            }
        });

        jToggleButton5.setText("Назначить тип");
        jToggleButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                assignSchema();
            }
        });

        setMinimumSize(new java.awt.Dimension(400, 330));
        setLocationRelativeTo(null);
        setAlwaysOnTop(true);
        setResizable(false);

        javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(jDialog2Layout);
        jDialog2Layout.setHorizontalGroup(
                jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 400, Short.MAX_VALUE)
                        .addComponent(jTabbedPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDialog2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jToggleButton5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 166, Short.MAX_VALUE)
                                .addComponent(jToggleButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
        );
        jDialog2Layout.setVerticalGroup(
                jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 303, Short.MAX_VALUE)
                        .addGroup(jDialog2Layout.createSequentialGroup()
                                .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jToggleButton4)
                                        .addComponent(jToggleButton5))
                                .addContainerGap())
        );
        pack();
    }

    public ItemInfo showDialog() {
        setVisible(true);
        typesList1.ensureIndexIsVisible(curentType);
        schemasList1.ensureIndexIsVisible(currentSchema);
        return null;
    }

    public void changeTitle(String title) {
        setTitle(title);
    }

    public void assignSchema() {

        AuthorElement authorNode = docController.getAuthorDocumentNode().getRootElement();
        docController.setAttribute("xmlns:xsi", new AttrValue("http://www.w3.org/2001/XMLSchema-instance"), authorNode);
        if (jTabbedPane2.getSelectedIndex() == 0)//doctype & schema change
            if (typesList1.getSelectedIndex() != -1) {
                ItemInfo selected = (ItemInfo) typesList1.getSelectedValue();
                docController.setAttribute("type", new AttrValue(selected.id), authorNode);
                docController.setAttribute("xsi:noNamespaceSchemaLocation", new AttrValue(selected.url), authorNode);
            }
        if (jTabbedPane2.getSelectedIndex() == 1)//schema change
            if (schemasList1.getSelectedIndex() != -1) {
                ItemInfo selected = (ItemInfo) schemasList1.getSelectedValue();
                //if (authorNode.getAttribute("type").getValue().isEmpty()){
                docController.setAttribute("xsi:noNamespaceSchemaLocation", new AttrValue(selected.url), authorNode);
                //}
            }

        closeSchemaSelectionFrame();
    }

    public void closeSchemaSelectionFrame() {
        setVisible(false);
    }

    public void showSchemaSelectionFrame() {
        setVisible(true);
    }

}
